package com.elitel.frame.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elitel.frame.base.component.RedisCacheCfgMaster;
import com.elitel.frame.base.component.RedisCacheProjectService;
import com.elitel.frame.base.service.BaseMasterdetailService;
import com.elitel.frame.base.service.BaseShowfieldService;
import com.elitel.frame.base.service.CfgExtmasterService;
import com.elitel.frame.main.dao.CfgDbMapper;
import com.elitel.frame.main.dao.CfgExtmasterMapper;
import com.elitel.frame.main.dao.SysPrjserviceMapper;
import com.elitel.frame.main.dao.ext.ExtBaseFieldaddonsMapper;
import com.elitel.frame.main.dao.ext.ExtBaseFieldconfigMapper;
import com.elitel.frame.main.dao.ext.ExtBaseMasterdetailMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQueryfieldMapper;
import com.elitel.frame.main.dao.ext.ExtBaseQuerysqlMapper;
import com.elitel.frame.main.dao.ext.ExtBaseShowfieldMapper;
import com.elitel.frame.main.dao.ext.ExtCfgDbMapper;
import com.elitel.frame.main.dao.ext.ExtCfgExtmasterMapper;
import com.elitel.frame.main.dao.ext.ExtCfgFieldMapper;
import com.elitel.frame.main.dao.ext.ExtCfgTableMapper;
import com.elitel.frame.main.entity.BaseMasterdetail;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgExtmaster;
import com.elitel.frame.main.entity.CfgField;
import com.elitel.frame.main.entity.CfgTable;
import com.elitel.frame.main.entity.SysPrjservice;
import com.elitel.frame.main.entity.ext.BaseFieldaddonsExt;
import com.elitel.frame.main.entity.ext.BaseShowfieldExt;
import com.elitel.frame.main.entity.ext.CfgExtmasterExt;
import com.elitel.frame.main.entity.vo.KeyValueModelVo;
import com.elitel.frame.main.entity.vo.ZTreeDataModelVo;

/**
 * @Description 主从表配置服务接口实现类
 * @author guoyanfei
 */
@Service
public class CfgExtmasterServiceImpl implements CfgExtmasterService {
	@Autowired
	private ExtCfgExtmasterMapper extCfgExtmasterMapper;
	@Autowired
	private ExtCfgDbMapper extCfgDbMapper;
	@Autowired
	private CfgExtmasterMapper cfgExtmasterMapper;
	@Autowired
	private ExtBaseMasterdetailMapper extBaseMasterdetailMapper;
	@Autowired
	private RedisCacheCfgMaster redisCacheCfgMaster;
	@Autowired
	private ExtCfgTableMapper extCfgTableMapper;
	@Autowired
	private ExtCfgFieldMapper extCfgFieldMapper;
	@Autowired
	private ExtBaseFieldaddonsMapper extBaseFieldaddonsMapper;
	@Autowired
	private ExtBaseFieldconfigMapper extBaseFieldconfigMapper;
	@Autowired
	private ExtBaseQueryfieldMapper extBaseQueryfieldMapper;
	@Autowired
	private BaseShowfieldService baseShowfieldService;
	@Autowired
	private BaseMasterdetailService baseMasterdetailService;
	@Autowired
	private SysPrjserviceMapper sysPrjserviceMapper;
	@Autowired
	private ExtBaseQuerysqlMapper extBaseQuerysqlMapper;
	@Autowired
	private CfgDbMapper cfgDbMapper;
	@Autowired
	private RedisCacheProjectService redisCacheProjectService;
	@Autowired
	private ExtBaseShowfieldMapper extBaseShowfieldMapper;
	
	@Override
	public List<ZTreeDataModelVo> getmasterDetailTree() {
		List<ZTreeDataModelVo> treelist = new ArrayList<>();
		List<CfgDb> cfgdblist = extCfgDbMapper.getAllListCfgDb();
		if(cfgdblist != null ){
			for (CfgDb cfgDb : cfgdblist) {
				ZTreeDataModelVo treeDataModelVo = new ZTreeDataModelVo();
				treeDataModelVo.setId(cfgDb.getDbKey());
				treeDataModelVo.setName(cfgDb.getDbMark()+"("+cfgDb.getDbName()+")");
				treeDataModelVo.setHint("数据库:"+cfgDb.getDbName());
				treeDataModelVo.setIsMark("0");
				
				//通过dbkey查询主从表服务
				List<CfgExtmaster> cfgExtmasters = extCfgExtmasterMapper.getdataBydbKey(cfgDb.getDbKey());
				if(cfgExtmasters != null){
					List<ZTreeDataModelVo> ztreeChildrenList = new ArrayList<>();
					for (CfgExtmaster cfgExtmaster : cfgExtmasters) {
						ZTreeDataModelVo ztreechildren = new ZTreeDataModelVo();
						ztreechildren.setId(cfgExtmaster.getGuid());
						ztreechildren.setName(cfgExtmaster.getServicename());
						ztreechildren.setHint("服务ID:"+cfgExtmaster.getGuid());
						ztreechildren.setIsMark("1");
						ztreeChildrenList.add(ztreechildren);
					}
					treeDataModelVo.setChildren(ztreeChildrenList);
				}
				treelist.add(treeDataModelVo);
			}
		}
		return treelist;
	}

	@Override
	public boolean isExistGuid(String guid) {
		boolean result = true;
		CfgExtmaster cfgExtmaster = cfgExtmasterMapper.selectByPrimaryKey(guid);
		if(cfgExtmaster != null){
			result = false;
		}
		return result;
	}

	@Override
	public Integer insertMasterdata(CfgExtmaster cfgExtmaster) {
		Date nowtime = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cfgExtmaster.setCreatedate(dateFormat.format(nowtime));
		int in = cfgExtmasterMapper.insertSelective(cfgExtmaster);
		redisCacheCfgMaster.freshCfgMasterRedisCache();
		return in;
	}

	@Override
	public Integer updateMasterdata(CfgExtmaster cfgExtmaster) {
		//修改时，检查是否修改表表面，如修改，则修改删除已配置的显示列，查询列等表
		CfgExtmaster cfgExtmasterold = cfgExtmasterMapper.selectByPrimaryKey(cfgExtmaster.getGuid());
		if(!cfgExtmaster.getDtConfigId().equals(cfgExtmasterold.getDtConfigId())){
			//删除显示字段
			extBaseShowfieldMapper.deleteShowfieldByServiceId(cfgExtmaster.getGuid());
			//删除查询字段
			extBaseQueryfieldMapper.deleteQueryfieldByServiceId(cfgExtmaster.getGuid());
			//删除查找sql文
			extBaseQuerysqlMapper.deleteQuerysqlByServiceId(cfgExtmaster.getGuid());
		}
		int in = cfgExtmasterMapper.updateByPrimaryKeySelective(cfgExtmaster);
		redisCacheCfgMaster.freshCfgMasterRedisCache();
		return in;
	}

	@Override
	public Integer deleteMasterdata(String guid) {
		Integer result = 0;
		//删除主表显示列信息
		List<BaseShowfieldExt> baseShowfieldExts = baseShowfieldService.getShowfieldList(guid,"2","");
		if(baseShowfieldExts != null && baseShowfieldExts.size() > 0){
			String strshowguid = "";
			for (BaseShowfieldExt baseShowfieldExt : baseShowfieldExts) {
				if(strshowguid == null || strshowguid.equals("")){
					strshowguid+=baseShowfieldExt.getGuid();
				}else{
					strshowguid+=","+baseShowfieldExt.getGuid();
				}
			}
			result += baseShowfieldService.deleteShowfieldByguids(strshowguid);
		}
		
		//删除主表查询字段
		result += extBaseQueryfieldMapper.deleteQueryfieldByServiceId(guid);
		//删除查询字段条件sql
		result += extBaseQuerysqlMapper.deleteQuerysqlByServiceId(guid);
		//删除主表
		result += cfgExtmasterMapper.deleteByPrimaryKey(guid);
		//删除从表
		List<BaseMasterdetail> baseMasterdetails = baseMasterdetailService.getMasterdetailByguid(guid);
		if(baseMasterdetails != null && baseMasterdetails.size() > 0){
			for (BaseMasterdetail baseMasterdetail : baseMasterdetails) {
				result += baseMasterdetailService.deleteMasterDetail(baseMasterdetail.getGuid());
			}
		}
		
		//刷新缓存
		redisCacheCfgMaster.freshCfgMasterRedisCache();
		return result;
	}

	@Override
	public CfgExtmaster getCfgExtmasterByguid(String guid) {
		return cfgExtmasterMapper.selectByPrimaryKey(guid);
	}

	@Override
	public List<CfgExtmaster> selectAllExtMaster() {
		List<CfgExtmaster> list = extCfgExtmasterMapper.selectAllExtMaster();
		return list;
	}

	@Override
	public List<KeyValueModelVo> selectFieldValue(String dtConfigId) {
		List<KeyValueModelVo> keyValueModelVos = new ArrayList<>();
		CfgTable cfgTable = extCfgTableMapper.getInfoByDtconfigId(dtConfigId);
		if(cfgTable != null){
			if(cfgTable.getDtTabletype() == 1){
				//数据表
				List<CfgField> cfgFields = extCfgFieldMapper.getAllFieldList(dtConfigId);
				if(cfgFields != null && cfgFields.size() > 0){
					for (CfgField cfgField : cfgFields) {
						KeyValueModelVo keyValueModelVo = new KeyValueModelVo();
						keyValueModelVo.setKey(cfgField.getGuid());
						keyValueModelVo.setValue(cfgField.getDfNameCn()+"("+cfgField.getDfName()+")");
						keyValueModelVos.add(keyValueModelVo);
					}
				}
			}else if(cfgTable.getDtTabletype() == 2){
				//视图
				CfgTable cfgView = extCfgTableMapper.getInfoByDtconfigId(dtConfigId);
				if(cfgView != null){
					List<BaseFieldaddonsExt> fieldaddonslist = 
							extBaseFieldaddonsMapper.getBaseFieldaddonsByPage(dtConfigId);
					if(fieldaddonslist != null){
						for (BaseFieldaddonsExt baseFieldaddonsExt : fieldaddonslist) {
							//查询字段对应表别名
							String tablealterName = baseFieldaddonsExt.getAltername();
							KeyValueModelVo keyValueModelVo = new KeyValueModelVo();
							keyValueModelVo.setKey(baseFieldaddonsExt.getGuid());
							if(baseFieldaddonsExt.getIsmodfcaption() != null && baseFieldaddonsExt.getIsmodfcaption() ==1){
								keyValueModelVo.setValue((baseFieldaddonsExt.getModifieldcaption().equals("") == false ? 
										baseFieldaddonsExt.getModifieldcaption() : baseFieldaddonsExt.getFieldnameCn())+
										"("+baseFieldaddonsExt.getFieldname()+")");
							}else{
								keyValueModelVo.setValue(baseFieldaddonsExt.getFieldnameCn()+"("+baseFieldaddonsExt.getFieldname()+")");
							}
							keyValueModelVos.add(keyValueModelVo);
						}
					}
				}
			}
		}
		return keyValueModelVos;
	}

	@Override
	public Integer insertMasterandSysprj(CfgExtmasterExt cfgExtmasterExt) {
		Integer result = 0;
		//添加主表信息
		CfgExtmaster cfgExtmaster = new CfgExtmaster();
		cfgExtmaster.setGuid(cfgExtmasterExt.getGuid());
		cfgExtmaster.setServicename(cfgExtmasterExt.getServicename());
		cfgExtmaster.setDbKey(cfgExtmasterExt.getDbKey());
		cfgExtmaster.setDtConfigId(cfgExtmasterExt.getDtConfigId());
		cfgExtmaster.setRemark(cfgExtmasterExt.getRemark());
		cfgExtmaster.setIspagination(cfgExtmasterExt.getIspagination());
		cfgExtmaster.setSyscatch(cfgExtmasterExt.getSyscatch());
		cfgExtmaster.setCatchtime(cfgExtmasterExt.getCatchtime());
		cfgExtmaster.setResponseMode(cfgExtmasterExt.getResponseMode());
		Date datenow = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cfgExtmaster.setCreatedate(dateFormat.format(datenow));
		
		result += cfgExtmasterMapper.insertSelective(cfgExtmaster);
		
		//添加工程服务表信息
		SysPrjservice sysPrjservice = new SysPrjservice();
		sysPrjservice.setGuid(UUID.randomUUID().toString());
		sysPrjservice.setPcode(cfgExtmasterExt.getPcode());
		sysPrjservice.setServicetype(cfgExtmasterExt.getServicetype());
		sysPrjservice.setServicecode(cfgExtmasterExt.getGuid());
		sysPrjservice.setCreatedate(new Date());
		result += sysPrjserviceMapper.insertSelective(sysPrjservice);
		
		redisCacheCfgMaster.freshCfgMasterRedisCache();
		return result;
	}

	@Override
	public String getdbtypeByserviceId(String serviceId) {
		String result = "";
		CfgExtmaster cfgExtmaster = cfgExtmasterMapper.selectByPrimaryKey(serviceId);
		if(cfgExtmaster != null){
			CfgDb cfgDb = cfgDbMapper.selectByPrimaryKey(cfgExtmaster.getDbKey());
			if(cfgDb != null){
				result = cfgDb.getDbVersion();
			}
		}
		return result;
	}

	@Override
	public void deleteMasterdataByPrjservice(SysPrjservice prjservice) {
		sysPrjserviceMapper.deleteByPrimaryKey(prjservice.getGuid());
		//删除主表显示列信息
		List<BaseShowfieldExt> baseShowfieldExts = baseShowfieldService.getShowfieldList(prjservice.getServicecode(),"2","");
		if(baseShowfieldExts != null && baseShowfieldExts.size() > 0){
			String strshowguid = "";
			for (BaseShowfieldExt baseShowfieldExt : baseShowfieldExts) {
				if(strshowguid == null || strshowguid.equals("")){
					strshowguid+=baseShowfieldExt.getGuid();
				}else{
					strshowguid+=","+baseShowfieldExt.getGuid();
				}
			}
			baseShowfieldService.deleteShowfieldByguids(strshowguid);
		}
		
		//删除主表查询字段
		extBaseQueryfieldMapper.deleteQueryfieldByServiceId(prjservice.getServicecode());
		//删除查询字段条件sql
		extBaseQuerysqlMapper.deleteQuerysqlByServiceId(prjservice.getServicecode());
		//删除主表
		cfgExtmasterMapper.deleteByPrimaryKey(prjservice.getServicecode());
		//删除从表
		List<BaseMasterdetail> baseMasterdetails = baseMasterdetailService.getMasterdetailByguid(prjservice.getServicecode());
		if(baseMasterdetails != null && baseMasterdetails.size() > 0){
			for (BaseMasterdetail baseMasterdetail : baseMasterdetails) {
				baseMasterdetailService.deleteMasterDetail(baseMasterdetail.getGuid());
			}
		}
		
		//刷新缓存
		redisCacheCfgMaster.freshCfgMasterRedisCache();
		redisCacheProjectService.freshProjectServerTree();
	}
}
